﻿using Common.Contract.Customer.Record;
using Common.Contract.Customer.Request;
using Common.Contract.Customer.Response;
using Common.Service.Command;
using Customer.Model.Interface;
using Customer.Model.Model;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;

namespace Customer.Core.ServiceCommand
{
    public class RetrieveNewLendingInfoServiceCommand : ProviderServiceCommand<IProviderFactory, RetrieveNewLendingInfoRequest, RetrieveNewLendingInfoResponse>
    {
        #region Properties
        public string Cif;
        public int pageSize = 10, pageIndex = 0, totalRecord = 0;
        CultureInfo cul = CultureInfo.GetCultureInfo("vi-VN");   // try with "en-US"
        #endregion
        public RetrieveNewLendingInfoServiceCommand(IProviderFactory providers) : base(providers) { }
        protected override void Validate(RetrieveNewLendingInfoRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            if (!request.Header.ApplicationKey.HasValue || request.Header.ApplicationKey == Guid.Empty)
            {
                throw new ArgumentException("ApplicationKey must be set", "request");
            }
            if (string.IsNullOrEmpty(request.Cif))
            {
                throw new ArgumentException("Cif Customer must be set", "request");
            }
            else
            {
                Cif = Request.Cif;
            }
            if (Request.Page != null)
            {
                pageIndex = Request.Page.PageIndex ?? 0;
                pageSize = Request.Page.PageSize ?? 0;
            }
        }

        protected override bool OnExecute(RetrieveNewLendingInfoResponse response)
        {
            bool isSuccess = true;
            string errorMessage = string.Empty;
            List<NewLendingRecord> records = new List<NewLendingRecord>();
            List<NewLending> newLending = new List<NewLending>();
            newLending = Providers.Customers.RetrieveNewLendingByCif(Cif);
            if (newLending != null && newLending.Count > 0)
            {
                records = newLending.Select(x => new NewLendingRecord
                {
                    Cif = x.Cif,
                    CustName = x.CusName,
                    DistDate = x.DistDate.ToShortDateString(),
                    Acctno = x.Acctno,
                    MatDate = x.BalQd.ToString("#,###", cul.NumberFormat),
                    ChuongTrinhSp = x.ChuongTrinhSp
                }).ToList();
            }
            response.Records = records;

            return isSuccess;
        }
    }
}
